#include <iostream>
#include <unistd.h>
#include <vector>
#include <pthread.h>
#include "pthread.hpp"
#include "Block_Queue.hpp"
#include"Task.hpp"
using namespace pthread_moudle;

using _block_queue_t = BlockQueue<Task>;
int g_val = 10;
void ProductorTask(_block_queue_t &bq)
{
    srand(time(nullptr));
    while (true)
    { 
        sleep(1);
        int a=rand()%100,b=rand()%100;
        Task t(a,b);
        std::cout << "productor---push task data a: " << a <<",b: "<<b<< std::endl;
        bq.Enqueue(t);
    }
}

void ConsumerTask(_block_queue_t &bq)
{
    while (true)
    {
        sleep(1);
        Task out;
        bq.pop(&out);
        std::cout << "consumer---get result:  " << out.excute() << std::endl;
    }

}

// 启动生产者
void StartProductor(std::vector<Thread<_block_queue_t>> *Threads, int num, _block_queue_t &bq)
{
    for (int i = 0; i < num; i++)
    {
        std::string name = "productor---" + std::to_string(i + 1);
        Threads->emplace_back(ProductorTask, bq, name); // 直接构造对象进入vector数组
        Threads->back().start();                        // 启动该线程
    }
}

void StartConsumer(std::vector<Thread<_block_queue_t>> *Threads, int num, _block_queue_t &bq)
{
    for (int i = 0; i < num; i++)
    {
        std::string name = "consumer---" + std::to_string(i + 1);
        Threads->emplace_back(ConsumerTask, bq, name); // 直接构造对象进入vector数组
        Threads->back().start();                          // 启动该线程
    }
}

// 等待所有线程
void WaitPthread(std::vector<Thread<_block_queue_t>> Threads)
{
    for (auto td : Threads)
    {
        td.join();
    }
}
int main()
{
    _block_queue_t *bq = new _block_queue_t(5);
    std::vector<Thread<_block_queue_t>> Threads;

    // 启动生产者线程
    StartProductor(&Threads, 1, *bq);

    // 启动消费者线程
    StartConsumer(&Threads, 1, *bq);

    // 等待所有线程
    WaitPthread(Threads);
    return 0;
}